package cn.net.cfss.fgbp.provider.console.spi;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.net.cfss.fgbp.api.console.constant.DeleteFlagEnum;
import cn.net.cfss.fgbp.api.console.dto.SysRoleDto;
import cn.net.cfss.fgbp.api.console.dto.SysRoleMenuDto;
import cn.net.cfss.fgbp.api.console.dto.SysRoleProjectDto;
import cn.net.cfss.fgbp.api.console.dto.SysUserDto;
import cn.net.cfss.fgbp.api.console.dto.SysUserRoleDto;
import cn.net.cfss.fgbp.api.console.inte.ISysRoleService;
import cn.net.cfss.fgbp.api.console.vo.SysRoleVo;
import cn.net.cfss.fgbp.base.page.PageData;
import cn.net.cfss.fgbp.base.service.FeignBaseService;
import cn.net.cfss.fgbp.provider.console.biz.SysRoleDtoBiz;
import cn.net.cfss.fgbp.provider.console.biz.SysRoleMenuDtoBiz;
import cn.net.cfss.fgbp.provider.console.biz.SysRoleProjectDtoBiz;
import cn.net.cfss.fgbp.provider.console.biz.SysUserDtoBiz;
import cn.net.cfss.fgbp.provider.console.biz.SysUserRoleDtoBiz;
import cn.net.cfss.fgbp.provider.console.utils.FgbpIdUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author oygq
 * @title: IRoleServiceImpl
 * @description: TODO
 * @date 2019/4/2 19:21
 */

@RestController
@Slf4j
public class SysRoleServiceSpi extends FeignBaseService implements ISysRoleService {

    @Autowired
    SysRoleDtoBiz roleDtoBiz;

    @Autowired
    SysRoleMenuDtoBiz roleMenuDtoBiz;

    @Autowired
    SysUserRoleDtoBiz sysUserRoleDtoBiz;

    @Autowired
    SysRoleDtoBiz sysRoleDtoBiz;

    @Autowired
    SysRoleProjectDtoBiz roleProjectDtoBiz;
    
    @Autowired
    SysUserDtoBiz userDtoBiz;

    @Override
    public boolean insert(SysRoleVo role) {
        role.setCreateTime(new Date());
        role.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        role.setId(FgbpIdUtil.generateId());
        try {
        	SysUserDto user = userDtoBiz.selectById(getUserId());
            if(null != user.getServiceProvider()){
            	 role.setOrgId(user.getServiceProvider());
        	}
            roleDtoBiz.insert(role);
            //绑定项目
            if (role.getProjects() != null && role.getProjects().size() > 0) {
                roleProjectDtoBiz.add(role.getId(), role.getProjects());
            }
        } catch (Exception e) {
            log.error("角色新增错误:{}", e.getMessage());

            return false;
        }

        log.info("请求参数:{}，返回参数：{}", role, true);

        return true;
    }

    @Override
    public boolean update(SysRoleVo role) {
        role.setUpdateTime(new Date());
        try {
            roleDtoBiz.updateSelectiveById(role);
            //绑定项目
            roleProjectDtoBiz.updateByRoleId(role.getId(), role.getProjects());
        } catch (Exception e) {
            log.error("角色修改错误:{}", e.getMessage());
            return false;
        }

        log.info("请求参数:{}，返回参数：{}", role, true);

        return true;
    }

    @Override
    public boolean delete(Long roleId) {
        try {
            SysRoleVo vo = new SysRoleVo();
            vo.setId(Long.valueOf(roleId));
            vo.setUpdateTime(new Date());
            vo.setDeleteFlag(DeleteFlagEnum.DEL);
            roleDtoBiz.updateSelectiveById(vo);

            //删除角色缓存
            roleDtoBiz.deleteRoleAuthCache(roleId);
            //删除角色绑定的项目
            SysRoleProjectDto dto = new SysRoleProjectDto();
            dto.setRoleId(roleId);
            roleProjectDtoBiz.delete(dto);
        } catch (Exception e) {
            log.error("角色删除错误:{}", e.getMessage());
            return false;
        }

        log.info("请求参数:{}，返回参数：{}", roleId, true);
        return true;
    }

    @Override
    public boolean deleteBatch(List<Long> roleIds) {
        try {
            roleDtoBiz.deleteBatch(roleIds);
            //删除角色缓存
            roleDtoBiz.deleteRoleAuthCache(roleIds);
            //删除角色绑定的项目
            roleProjectDtoBiz.deleteBatch(roleIds);
        } catch (Exception e) {
            log.error("角色批量删除错误:{}", e.getMessage());
            return false;
        }

        log.info("请求参数:{}，返回参数：{}", roleIds, true);

        return true;
    }

    @Override
    public SysRoleVo queryById(Long roleId) {
        SysRoleDto dto = roleDtoBiz.selectById(Long.valueOf(roleId));
        SysRoleVo vo = new SysRoleVo();
        BeanUtils.copyProperties(dto, vo);
        //所绑定项目
        SysRoleProjectDto sysRoleProjectDto = new SysRoleProjectDto();
        sysRoleProjectDto.setRoleId(roleId);
        List<SysRoleProjectDto> roleProjectDtos = roleProjectDtoBiz.selectList(sysRoleProjectDto);
        List<String> projects = new ArrayList<String>();
        for (SysRoleProjectDto roleProjectDto : roleProjectDtos) {
            projects.add(roleProjectDto.getProjPkId());
        }
        vo.setProjIds(projects);
        return vo;
    }

    @Override
    public PageData<SysRoleDto> queryList(PageData<SysRoleDto> page) {
        PageData<SysRoleDto> req = page;

        boolean isSuperAdmin = false;
        //判断是否是超级管理员
        //查询用户的角色
        if (null != getUserId()) {
            SysUserRoleDto userRoleDto = new SysUserRoleDto();
            userRoleDto.setUserId(getUserId());
            List<SysUserRoleDto> roleList = sysUserRoleDtoBiz.selectList(userRoleDto);
            for (SysUserRoleDto u : roleList) {
                SysRoleDto roleDto = new SysRoleDto();
                roleDto.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
                roleDto.setId(u.getRoleId());
                roleDto = sysRoleDtoBiz.selectOne(roleDto);
                //超级管理员可以看所有
                if (null != roleDto && "super_admin".equals(roleDto.getRoleCode())) {
                    isSuperAdmin = true;
                    break;
                }
            }
        }
        SysUserDto user = userDtoBiz.selectById(getUserId());
        Long orgId = user.getServiceProvider();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        SysRoleDto search = page.getSearch();
        search.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        search.setOrgId(orgId);
        List<SysRoleDto> list = roleDtoBiz.queryList(search, isSuperAdmin);

        //Page<SysRoleDto> pageInfo = (Page<SysRoleDto>) list;
        Page<SysRoleDto> pageInfo = (Page<SysRoleDto>) list;
        page.setRows(list);
        page.setTotal(pageInfo.getTotal());

        log.info("请求参数:{}，返回参数：{}", req, page);

        return page;
    }

    @Override
    public List<String> queryByRoleId(Long roleId) {

        SysRoleMenuDto roleMenu = new SysRoleMenuDto();
        roleMenu.setId(roleId);
        List<SysRoleMenuDto> dto = roleMenuDtoBiz.selectList(roleMenu);
        List<String> menus = new ArrayList<>();
        for (SysRoleMenuDto r : dto) {
            menus.add(r.getMenuId() + "");
        }

        log.info("请求参数:{}，返回参数：{}", roleId, menus);

        return menus;
    }

    /**
     * 角色唯一性校验
     *
     * @param roleCode
     * @return
     */
    @Override
    public boolean uniquenessCheck(String roleCode, Long id) {
        try {
            boolean flag = roleDtoBiz.check(roleCode, id);

            log.info("请求参数:roleCode= {}，id= {},返回参数：{}", roleCode, id, flag);
            return flag;
        } catch (Exception e) {
            log.error("角色唯一校验错误:{}", e.getMessage());

            return false;
        }
    }
}
